package com.ydkj.a37e_mall.Classes.Fragment;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.qiniu.android.common.Zone;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;
import com.ydkj.a37e_mall.Classes.Acitivity.BaseActivity.ApplyBusinessActivity;
import com.ydkj.a37e_mall.Classes.Acitivity.BaseActivity.AuthenticationActivity;
import com.ydkj.a37e_mall.Classes.Acitivity.BaseActivity.BusinessRcvMoney;
import com.ydkj.a37e_mall.Classes.Acitivity.BaseActivity.ForgetPayid;
import com.ydkj.a37e_mall.Classes.Acitivity.BaseActivity.LoginActivity;
import com.ydkj.a37e_mall.Classes.Acitivity.BaseActivity.ManageAddressActivity;
import com.ydkj.a37e_mall.Classes.Acitivity.BaseActivity.MyAccountActivity;
import com.ydkj.a37e_mall.Classes.Acitivity.BaseActivity.MyBalanceAcitivity;
import com.ydkj.a37e_mall.Classes.Acitivity.BaseActivity.MyBankcardActivity;
import com.ydkj.a37e_mall.Classes.Acitivity.BaseActivity.MyBusinessActivity;
import com.ydkj.a37e_mall.Classes.Acitivity.BaseActivity.MyCollectionActivity;
import com.ydkj.a37e_mall.Classes.Acitivity.BaseActivity.MyInfo;
import com.ydkj.a37e_mall.Classes.Acitivity.BaseActivity.MyNewsActivity;
import com.ydkj.a37e_mall.Classes.Acitivity.BaseActivity.MyOrderActivity;
import com.ydkj.a37e_mall.Classes.Acitivity.BaseActivity.MyTbActivity;
import com.ydkj.a37e_mall.Classes.Acitivity.BaseActivity.MystoreActivity;
import com.ydkj.a37e_mall.Classes.Acitivity.BaseActivity.RecommendActivity;
import com.ydkj.a37e_mall.Classes.Acitivity.BaseActivity.SetUpActivity;
import com.ydkj.a37e_mall.Classes.Applicatiom.MyApplication;
import com.ydkj.a37e_mall.Classes.Model.Request.BusinessqfcatReq;
import com.ydkj.a37e_mall.Classes.Model.Request.EditAvatarReq;
import com.ydkj.a37e_mall.Classes.Model.Request.GetTreasureReq;
import com.ydkj.a37e_mall.Classes.Model.Request.LoginReq;
import com.ydkj.a37e_mall.Classes.Model.Request.OauthloginReq;
import com.ydkj.a37e_mall.Classes.Model.Request.StorethumbnailReq;
import com.ydkj.a37e_mall.Classes.Model.Request.StroreimgReq;
import com.ydkj.a37e_mall.Classes.Model.Request.TokenReq;
import com.ydkj.a37e_mall.Classes.Model.Response.GetTreasureResp;
import com.ydkj.a37e_mall.Classes.Model.Response.LoginResp;
import com.ydkj.a37e_mall.Classes.Model.Response.TokenResp;
import com.ydkj.a37e_mall.R;
import com.ydkj.a37e_mall.Resource.Utils.Async_http_get;
import com.ydkj.a37e_mall.Resource.Utils.Async_http_post;
import com.ydkj.a37e_mall.Resource.Utils.CommonUtil;
import com.ydkj.a37e_mall.Resource.Utils.Const;
import com.ydkj.a37e_mall.Resource.Utils.GsonImpl;
import com.ydkj.a37e_mall.Resource.Utils.Rsa;
import com.ydkj.a37e_mall.Resource.Utils.SharedPreferencesUtil;
import com.ydkj.a37e_mall.Resource.View.CustomProgressDialog;
import com.ydkj.a37e_mall.Resource.View.RoundImageView;

import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;

import static com.loopj.android.http.AsyncHttpClient.log;

/**
 * Created by Administrator on 2017/1/4.
 */

public class MyFg extends BaseFg implements View.OnClickListener {
    private View rootView;
    private Activity mActivity;
    private TextView tv_set, tv_login_out, tv_integral, tv_username, mybalance;
    private SharedPreferencesUtil sharedPreferencesUtil;
    private MyApplication myApplication;
    private LinearLayout lly_my_collect, lly_manage_address;
    private RelativeLayout rly_my_message, rly_my_tb, rly_mall_balance, rly_my_order, rly_my_recommend;
    private LinearLayout rly_store, rly_business, rly_customer_service_qq, rly_application_mercha, rly_identity_authentication, rly_cheques, rly_customer_service_bandcard, rly_customer_service_updapayid;

    private RoundImageView img_my_head;
    private PopupWindow mPopupWindow;
    private File tempFile;//调用系统拍照返回的图片的地址
    private static final int PICTURE_REQUEST_GALLERY = 1;// 拍照
    private static final int PHOTO_REQUEST_GALLERY = 2;// 从相册中选择
    private static final int PHOTO_REQUEST_CUT = 3;// 结果
    private String secret;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.my_fragment, container, false);
        }
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null) {
            parent.removeView(rootView);
        }

        return rootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mActivity = getActivity();
        initData(savedInstanceState);
        sharedPreferencesUtil = SharedPreferencesUtil.getInstance(mActivity);
        myApplication = MyApplication.getInstance();
        init();
    }

    //获取七牛的Token
    private void GetToken(final String data, final String key) {
        log.e("ssss", "qiniu");
        CustomProgressDialog.createDialog(mActivity).show();
        TokenReq req = new TokenReq();
        req.setType("avatar");
        req.setKey(key);
        try {
            log.e("ssss", "req.getSecret()===>" + req.getstring());
            String source = req.getstring();
            Rsa rsa = new Rsa();
            secret = rsa.encryptByPublic(source);
            log.e("ssss", "secret===>" + secret);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String url = Const.COMMON_ADDRESS + req.urlString();
        params.put("secret", secret);

        Async_http_get.get(url, params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                CustomProgressDialog.Dismiss();
                String errno = response.optString("errno");
                String errmsg = response.optString("errmsg");

                if (errno.equals("000")) {
                    TokenResp resp = GsonImpl.get().toObject(response.toString(), TokenResp.class);
                    PostQiniu(data, key, resp.getResult().getUptoken());
                }
                if (!errno.equals("000")) {
                    CommonUtil.showToast(mActivity, errmsg);

                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                CustomProgressDialog.Dismiss();
                log.e("ssss", "statusCode==>" + statusCode);
            }
        });

    }


    private void PostQiniu(String data, String key, String token) {
        Log.e("ssss", "33333");

        Log.e("ssss", "data==>" + data);
        Log.e("ssss", "key==>" + key);
        Log.e("ssss", "token==>" + token);

        //http上传,指定zone的具体区域
        Configuration config = new Configuration.Builder().zone(Zone.zone2).build();
        UploadManager uploadManager = new UploadManager(config);
//        data = <File对象、或 文件路径、或 字节数组>
//        String key = <指定七牛服务上的文件名，或 null>;
//        String token = <从服务端SDK获取>;
        uploadManager.put(data, key, token,
                new UpCompletionHandler() {
                    @Override
                    public void complete(String key, ResponseInfo info, JSONObject res) {
                        //res包含hash、key等信息，具体字段取决于上传策略的设置
                        if (info.isOK()) {
                            Log.e("ssss", "上次成功");
                            EditName(key);
                        } else {
                            Log.e("ssss", "上次失败");
                            //如果失败，这里可以把info信息上报自己的服务器，便于后面分析上传错误原因
                        }
                        Log.e("ssss", "qiniukey==>" + key);
//                        Log.e("ssss", "info==>" + info);
                        Log.e("ssss", "res==>" + res);
                    }
                }, null);

    }


    private void init() {
        sharedPreferencesUtil = SharedPreferencesUtil.getInstance(mActivity);
        myApplication = MyApplication.getInstance();

        tv_set = (TextView) rootView.findViewById(R.id.tv_set);
        tv_login_out = (TextView) rootView.findViewById(R.id.tv_login_out);
        tv_integral = (TextView) rootView.findViewById(R.id.tv_integral);
        tv_username = (TextView) rootView.findViewById(R.id.tv_username);
        mybalance = (TextView) rootView.findViewById(R.id.mybalance);
        lly_my_collect = (LinearLayout) rootView.findViewById(R.id.lly_my_collect);
        lly_manage_address = (LinearLayout) rootView.findViewById(R.id.lly_manage_address);
        rly_customer_service_updapayid = (LinearLayout) rootView.findViewById(R.id.rly_customer_service_updapayid);
        rly_my_message = (RelativeLayout) rootView.findViewById(R.id.rly_my_message);
        rly_my_tb = (RelativeLayout) rootView.findViewById(R.id.rly_my_tb);
        rly_mall_balance = (RelativeLayout) rootView.findViewById(R.id.rly_mall_balance);
        rly_my_order = (RelativeLayout) rootView.findViewById(R.id.rly_my_order);
        rly_my_recommend = (RelativeLayout) rootView.findViewById(R.id.rly_my_recommend);
        rly_store = (LinearLayout) rootView.findViewById(R.id.rly_store);
        rly_business = (LinearLayout) rootView.findViewById(R.id.rly_business);
        rly_customer_service_qq = (LinearLayout) rootView.findViewById(R.id.rly_customer_service_qq);
        rly_application_mercha = (LinearLayout) rootView.findViewById(R.id.rly_application_mercha);
        rly_identity_authentication = (LinearLayout) rootView.findViewById(R.id.rly_identity_authentication);
        rly_customer_service_bandcard = (LinearLayout) rootView.findViewById(R.id.rly_customer_service_bandcard);
        rly_cheques = (LinearLayout) rootView.findViewById(R.id.rly_cheques);
        img_my_head = (RoundImageView) rootView.findViewById(R.id.img_my_head);


        //有用
        if (myApplication.getDataEntity() == null) {
            rly_store.setVisibility(View.GONE);//门店
            rly_cheques.setVisibility(View.GONE);//商家收款
            rly_business.setVisibility(View.GONE);//我的业务
            rly_application_mercha.setVisibility(View.GONE);//申请商户
            rly_identity_authentication.setVisibility(View.GONE);//身份认证
            rly_customer_service_bandcard.setVisibility(View.GONE);//我的银行卡
            rly_customer_service_qq.setVisibility(View.VISIBLE);//qq客服
        }

        if (sharedPreferencesUtil.getAccessToken().equals("")) {
            myApplication.setDataEntity(null);
            sharedPreferencesUtil.setUsername("");
            sharedPreferencesUtil.setPassword("");
            sharedPreferencesUtil.setIntegral("");
            sharedPreferencesUtil.setAccessToken("");
        }
        if (myApplication.getDataEntity() == null) {
            tv_username.setText("点击登录");
        } else {
            tv_username.setText(myApplication.getDataEntity().getNickname());
            Log.e("url", "mobile==" + myApplication.getDataEntity().getNickname());
            Log.e("url", "Thumb==" + myApplication.getDataEntity().getThumb());
            ImageLoader.getInstance().displayImage(myApplication.getDataEntity().getThumb(), img_my_head, displayImageOptions);
        }


        if (myApplication.getDataEntity() == null) {
            tv_login_out.setVisibility(View.GONE);
        } else {
            tv_login_out.setVisibility(View.VISIBLE);

        }

        tv_set.setOnClickListener(this);
        tv_login_out.setOnClickListener(this);
        tv_username.setOnClickListener(this);
        lly_my_collect.setOnClickListener(this);
        lly_manage_address.setOnClickListener(this);
        rly_my_message.setOnClickListener(this);
        rly_my_tb.setOnClickListener(this);
        rly_mall_balance.setOnClickListener(this);
        rly_my_order.setOnClickListener(this);
        rly_my_recommend.setOnClickListener(this);
        rly_store.setOnClickListener(this);
        rly_cheques.setOnClickListener(this);
        rly_business.setOnClickListener(this);
        rly_application_mercha.setOnClickListener(this);
        rly_identity_authentication.setOnClickListener(this);
        rly_customer_service_bandcard.setOnClickListener(this);
        rly_customer_service_qq.setOnClickListener(this);
        rly_customer_service_updapayid.setOnClickListener(this);
        img_my_head.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        WindowManager.LayoutParams lp;
        Intent intent = null;
        if (myApplication.getDataEntity() == null) {
            tv_username.setText("点击登录");
            switch (v.getId()) {
                case R.id.img_my_head://头像
                    startActivity(new Intent(mActivity, LoginActivity.class));

                    break;
                case R.id.tv_set://设置
                    startActivity(new Intent(mActivity, SetUpActivity.class));

                    break;
                case R.id.tv_login_out://退出登录

//                startActivity(new Intent(mActivity, LoginActivity.class));

                    break;
                case R.id.tv_username://账号名
                    startActivity(new Intent(mActivity, LoginActivity.class));

                    break;
                case R.id.lly_my_collect://我的收藏
                    startActivity(new Intent(mActivity, LoginActivity.class));

                    break;
                case R.id.lly_manage_address://管理地址
                    startActivity(new Intent(mActivity, LoginActivity.class));

                    break;
                case R.id.rly_my_message://我的消息
                    startActivity(new Intent(mActivity, LoginActivity.class));

                    break;
                case R.id.rly_my_tb://我的通宝
                    startActivity(new Intent(mActivity, LoginActivity.class));

                    break;
                case R.id.rly_mall_balance://我的余额
                    startActivity(new Intent(mActivity, LoginActivity.class));

                    break;
                case R.id.rly_my_order://我的订单
                    startActivity(new Intent(mActivity, LoginActivity.class));

                    break;
                case R.id.rly_my_recommend://分销推荐
                    startActivity(new Intent(mActivity, LoginActivity.class));

                    break;
                case R.id.rly_store://我的门店
                    startActivity(new Intent(mActivity, LoginActivity.class));

                    break;
                case R.id.rly_business://我的业务
                    startActivity(new Intent(mActivity, LoginActivity.class));

                    break;
                case R.id.rly_customer_service_qq://客服QQ
                    String url = "mqqwpa://im/chat?chat_type=wpa&uin=2881752100&version=1";
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));

                    break;
                case R.id.rly_application_mercha://申请商户
                    startActivity(new Intent(mActivity, LoginActivity.class));

                    break;
                case R.id.rly_identity_authentication://身份认证
                    startActivity(new Intent(mActivity, LoginActivity.class));

                    break;
                case R.id.rly_cheques://商家收款
                    startActivity(new Intent(mActivity, LoginActivity.class));

                    break;
                case R.id.rly_customer_service_bandcard://我的银行卡
                    startActivity(new Intent(mActivity, LoginActivity.class));
                    break;
            }

        } else {
            switch (v.getId()) {
                case R.id.img_my_head://头像

                    showPopulwindow();
                    lp = mActivity.getWindow().getAttributes();
                    lp.alpha = 0.5f;
                    mActivity.getWindow().setAttributes(lp);
                    mPopupWindow.showAtLocation(v, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
                    break;
                case R.id.tv_set://设置
                    startActivity(new Intent(mActivity, SetUpActivity.class));

                    break;
                case R.id.tv_login_out://退出登录


                    myApplication.setDataEntity(null);


                    rly_store.setVisibility(View.GONE);//门店
                    rly_cheques.setVisibility(View.GONE);//商家收款
                    rly_business.setVisibility(View.GONE);//我的业务
                    rly_application_mercha.setVisibility(View.GONE);//申请商户
                    rly_identity_authentication.setVisibility(View.GONE);//身份认证
                    rly_customer_service_bandcard.setVisibility(View.GONE);//我的银行卡
                    rly_customer_service_qq.setVisibility(View.VISIBLE);//qq客服

                    sharedPreferencesUtil.setUsername("");
                    sharedPreferencesUtil.setPassword("");
                    sharedPreferencesUtil.setIntegral("");
                    sharedPreferencesUtil.setAccessToken("");

                    sharedPreferencesUtil.setOpen_id("");
                    sharedPreferencesUtil.setType("");
                    Log.e("ssss", "my_username==>" + sharedPreferencesUtil.getUsername());
                    CommonUtil.showToast(mActivity, "已退出登录");
                    tv_username.setText("点击登录");
                    tv_integral.setText("");
                    tv_login_out.setVisibility(View.GONE);

                    break;
                case R.id.tv_username://账号名
                    intent = new Intent(mActivity, MyInfo.class);
                    intent.putExtra("name", tv_username.getText().toString());
                    startActivity(intent);
                    break;
                case R.id.lly_my_collect://我的收藏
                    startActivity(new Intent(mActivity, MyCollectionActivity.class));

                    break;
                case R.id.lly_manage_address://管理地址
                    startActivity(new Intent(mActivity, ManageAddressActivity.class));

                    break;
                case R.id.rly_my_message://我的消息
                    startActivity(new Intent(mActivity, MyNewsActivity.class));

                    break;
                case R.id.rly_my_tb://我的通宝
                    startActivity(new Intent(mActivity, MyTbActivity.class));

                    break;
                case R.id.rly_mall_balance://我的余额
                    startActivity(new Intent(mActivity, MyBalanceAcitivity.class));

                    break;
                case R.id.rly_my_order://我的订单
                    startActivity(new Intent(mActivity, MyOrderActivity.class));

                    break;
                case R.id.rly_my_recommend://分销推荐
                    startActivity(new Intent(mActivity, RecommendActivity.class));

                    break;
                case R.id.rly_store://我的门店
                    startActivity(new Intent(mActivity, MystoreActivity.class));

                    break;
                case R.id.rly_business://我的业务
                    startActivity(new Intent(mActivity, MyBusinessActivity.class));

                    break;
                case R.id.rly_customer_service_qq://客服QQ
                    String url = "mqqwpa://im/chat?chat_type=wpa&uin=2881752100&version=1";
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));

                    break;
                case R.id.rly_application_mercha://申请商户

                    if (myApplication.getDataEntity().getIs_store() == 0) {
                        myApplication.setStorename3("");
                        myApplication.setMobile3("");
                        myApplication.setAddress3("");
                        myApplication.setDescription3("");
                        myApplication.setName3("");
                        myApplication.setMobile3("");
                        myApplication.setIDnumber3("");
                        myApplication.setBanknumber3("");
                        myApplication.setBankname3("");
                        myApplication.setPaypswd3("");
                        myApplication.setPaypswd3_1("");


                        List<StroreimgReq> stroreimglist = new ArrayList<>();
                        myApplication.setStroreimglist(stroreimglist);
                        List<StorethumbnailReq> stroredetailslist = new ArrayList<>();
                        myApplication.setStroredetailslist(stroredetailslist);
                        List<BusinessqfcatReq> businessqfcatlist = new ArrayList<>();
                        myApplication.setBusinessqfcatlist(businessqfcatlist);

                        myApplication.setProvince3("");
                        myApplication.setProvince_id3("");
                        myApplication.setCity3("");
                        myApplication.setCity_id3("");
                        myApplication.setArea3("");
                        myApplication.setArea_id3("");
                        myApplication.setArea_code3("");
                        myApplication.setLocation3("");
                        myApplication.setLocation_id3("");

                        myApplication.setIntent_code(4);
                        startActivity(new Intent(mActivity, ApplyBusinessActivity.class));
                    } else if (myApplication.getDataEntity().getIs_store() == 1) {

                        CommonUtil.showToast(mActivity, "等待市场经理审核");
                        return;
                    } else if (myApplication.getDataEntity().getIs_store() == 2) {
                        CommonUtil.showToast(mActivity, "等待区域代理审核");

                        return;
                    } else if (myApplication.getDataEntity().getIs_store() == 3) {
                        CommonUtil.showToast(mActivity, "等待平台审核");
                        return;
                    } else if (myApplication.getDataEntity().getIs_store() == 4) {
                        CommonUtil.showToast(mActivity, "申请商家成功");
                        return;
                    }


                    break;
                case R.id.rly_identity_authentication://身份认证
//                    myApplication.setProvince2("");
//                    myApplication.setProvince_id2("");
//                    myApplication.setCity2("");
//                    myApplication.setCity_id2("");
//                    myApplication.setArea2("");
//                    myApplication.setArea_id2("");
//                    myApplication.setArea_code2("");
//                    myApplication.setLocation2("");
                    if (myApplication.getDataEntity().getIs_certificate().equals("2")) {
                        CommonUtil.showToast(mActivity, "正在审核中");
                        return;
                    }
                    if (myApplication.getDataEntity().getMobile().length() == 11) {

//                        myApplication.setName2("");
//                        myApplication.setMobile2("");
//                        myApplication.setIDnumber2("");
//                        myApplication.setPathurl2("");
//                        myApplication.setBanknumber2("");
//                        myApplication.setBankname2("");
//                        myApplication.setPaypswd2("");
//                        myApplication.setPaypswd2_1("");
//                        myApplication.setVerificationcode2("");
//                        myApplication.setSeekbarnum2("0");
//                        List<IdcardReq> pathlist = new ArrayList<>();
//                        myApplication.setPathlist(pathlist);
//                        myApplication.setPathlist(pathlist);
//                        myApplication.setIdimgnum2(0);
                        startActivity(new Intent(mActivity, AuthenticationActivity.class));
                    } else {
                        CommonUtil.showToast(mActivity, "请先绑定手机号");
                        startActivity(new Intent(mActivity, MyAccountActivity.class));
                    }


                    break;
                case R.id.rly_cheques://商家收款
                    startActivity(new Intent(mActivity, BusinessRcvMoney.class));

                    break;
                case R.id.rly_customer_service_bandcard://我的银行卡
                    startActivity(new Intent(mActivity, MyBankcardActivity.class));
                    break;
                case R.id.rly_customer_service_updapayid://修改支付密码
                    startActivity(new Intent(mActivity, ForgetPayid.class));

                    break;
            }
        }
    }

    private void showPopulwindow() {

        View contentView = LayoutInflater.from(mActivity).inflate(R.layout.photopopuwindows, null);
        TextView popul_photo = (TextView) contentView.findViewById(R.id.popul_photo);
        TextView popul_album = (TextView) contentView.findViewById(R.id.popul_album);
        TextView popul_cancel = (TextView) contentView.findViewById(R.id.popul_cancel);


        //拍照
        popul_photo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempFile));


//                intent.setType("image/*");
                // 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_GALLERY
                startActivityForResult(intent, PICTURE_REQUEST_GALLERY);
                mPopupWindow.dismiss();
            }
        });

        //相册
        popul_album.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_PICK);
                intent.setType("image/*");
                // 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_GALLERY
                startActivityForResult(intent, PHOTO_REQUEST_GALLERY);
                mPopupWindow.dismiss();
            }
        });
        popul_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPopupWindow.dismiss();
            }
        });


        mPopupWindow = new PopupWindow(contentView, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT, true);
        mPopupWindow.setTouchable(true);

        mPopupWindow.setAnimationStyle(R.style.mypopwindow_anim_style);

        ColorDrawable dw = new ColorDrawable(0x00000000);
        //设置PopupWindow弹出窗体的背景
        mPopupWindow.setBackgroundDrawable(dw);
        mPopupWindow.setOutsideTouchable(true);
        mPopupWindow.setFocusable(true);
        mPopupWindow.setTouchInterceptor(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {

                Log.i("mengdd", "onTouch : ");

                return false;
                // 这里如果返回true的话，touch事件将被拦截
                // 拦截后 PopupWindow的onTouchEvent不被调用，这样点击外部区域无法dismiss
            }
        });
//        mPopupWindow.setBackgroundDrawable(getResources().getDrawable(R.color.colorAccent));

        mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {

                WindowManager.LayoutParams lp = mActivity.getWindow().getAttributes();
                lp.alpha = 1;
                mActivity.getWindow().setAttributes(lp);
            }
        });

    }

    //获取通宝
    private void GetTb() {
        GetTreasureReq req = new GetTreasureReq();

        if (myApplication.getDataEntity() == null) {
            return;
        } else {
            req.setUuid(myApplication.getDataEntity().getUuid());
        }

        req.setType("1");
        RequestParams params = new RequestParams();
        params.put("token", sharedPreferencesUtil.getAccessToken());
        params.put("secret", req.getSecret());
        Async_http_get.get(Const.COMMON_ADDRESS + req.urlString(), params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);

                String errno = response.optString("errno");
                String errmsg = response.optString("errmsg");
                Log.e("url", "response==" + response);
                if (errno.equals("000")) {
                    GetTreasureResp resp = GsonImpl.get().toObject(response.toString(), GetTreasureResp.class);
                    //通宝
                    tv_integral.setText(resp.getResult().getData().getTreasure());
                    GetTreasure();
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
            }
        });
    }

    //获取我的余额
    private void GetTreasure() {
        GetTreasureReq req = new GetTreasureReq();
        req.setUuid(myApplication.getDataEntity().getUuid());
        req.setType("4");

        RequestParams params = new RequestParams();
        params.put("token", sharedPreferencesUtil.getAccessToken());
        params.put("secret", req.getSecret());
        Async_http_get.get(Const.COMMON_ADDRESS + req.urlString(), params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                String errno = response.optString("errno");
                String errmsg = response.optString("errmsg");
                Log.e("url", "response==" + response);
                if (errno.equals("000")) {
                    GetTreasureResp resp = GsonImpl.get().toObject(response.toString(), GetTreasureResp.class);
                    mybalance.setText(resp.getResult().getData().getBalance());

                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
            }
        });
    }

    //自动登录
    private void AutoLogin() {
        Log.e("ssss1", "账号密码登录==>");


        LoginReq req = new LoginReq();
        String url = Const.COMMON_ADDRESS + req.urlString();
        req.setMobile(sharedPreferencesUtil.getUsername());
        req.setPassword(sharedPreferencesUtil.getPassword());
        if (!myApplication.getChannelID().equals("")) {
            req.setAlias(myApplication.getChannelID());
        }
        req.setDevice_type(3);
        RequestParams params = new RequestParams();
        try {
            String source = req.getString();
            Log.e("url", "source==" + source);
            Rsa rsa = new Rsa();
            secret = rsa.encryptByPublic(source);
        } catch (Exception e) {
            e.printStackTrace();
        }
        params.put("secret", secret);
        Async_http_post.post(url, params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                if (statusCode == 200) {
                    String errno = response.optString("errno");
                    String errmsg = response.optString("errmsg");
                    Log.e("url", "json2==" + response);

                    Log.e("url", "登录返回json2==" + CommonUtil.format(response + ""));

                    if (errno.equals("000")) {
                        LoginResp resp = GsonImpl.get().toObject(response.toString(), LoginResp.class);
                        sharedPreferencesUtil.setAccessToken(resp.getResult().getAccess_token());
                        myApplication.setDataEntity(resp.getResult().getData());


                        if (myApplication.getDataEntity() == null) {
                            tv_username.setText("点击登录");
                        } else {
                            tv_username.setText(myApplication.getDataEntity().getNickname());
                            ImageLoader.getInstance().displayImage(myApplication.getDataEntity().getThumb(), img_my_head, displayImageOptions);


                            tv_login_out.setVisibility(View.VISIBLE);
                            inittype();
                            GetTb();

                        }
                    }
                    if (!errno.equals("000")) {
                    }
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                CommonUtil.showToast(mActivity, "网络连接失败");
            }
        });
    }

    //第三方登录
    private void Oauth_login() {
        Log.e("ssss1", "第三方登录==>");
        OauthloginReq req = new OauthloginReq();
        req.setOpenid(sharedPreferencesUtil.getOpen_id());
        req.setType(sharedPreferencesUtil.getType() + "");
        req.setAlias(myApplication.getChannelID());
        req.setDevice_type("3");
        req.setNickname(sharedPreferencesUtil.getNickname());
        req.setAvatar(sharedPreferencesUtil.getAvatar());
        RequestParams params = new RequestParams();
        params.put("secret", req.getSecret());

        Async_http_post.post(Const.COMMON_ADDRESS + req.urlString(), params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                String errno = response.optString("errno");
                String errmag = response.optString("errmsg");
                Log.e("ssss", "第三方==" + response);
                if (errno.equals("000")) {

                    LoginResp resp = GsonImpl.get().toObject(response.toString(), LoginResp.class);
                    sharedPreferencesUtil.setAccessToken(resp.getResult().getAccess_token());
                    myApplication.setDataEntity(resp.getResult().getData());

                    if (myApplication.getDataEntity() == null) {
                        tv_username.setText("点击登录");
                    } else {
                        tv_username.setText(myApplication.getDataEntity().getNickname());
                        ImageLoader.getInstance().displayImage(myApplication.getDataEntity().getThumb(), img_my_head, displayImageOptions);
                        inittype();
                        GetTb();
                        tv_login_out.setVisibility(View.VISIBLE);
                    }
                }
            }


            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                CustomProgressDialog.Dismiss();
                CommonUtil.showToast(mActivity, "网络连接失败");
            }
        });

    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.e("ssss", "requestCode==>" + requestCode);
        if (requestCode == PHOTO_REQUEST_GALLERY) {
            // 从相册返回的数据
            if (data != null) {
                // 得到图片的全路径
                Log.e("ssss", "相册返回");

                Uri uri = data.getData();
                Log.e("ssss", "Uri" + uri);

                crop(uri);
            }
        } else if (requestCode == PHOTO_REQUEST_CUT) {
            // 从剪切图片返回的数据

            Log.e("ssss", "裁剪返回");

            if (data != null) {
                Bitmap bitmap = data.getParcelableExtra("data");
                img_my_head.setImageBitmap(bitmap);
                String imgpath = CommonUtil.getBitmapToPaths(mActivity, bitmap);
                log.e("ssss", "imgpath==>" + imgpath);

                log.e("ssss", "imgpath1111==>" + imgpath.substring(imgpath.lastIndexOf("/"), imgpath.length()));
                GetToken(imgpath, "avatar" + imgpath.substring(imgpath.lastIndexOf("/"), imgpath.length()));
            }
            try {
                // 将临时文件删除
                tempFile.delete();
            } catch (Exception e) {
                e.printStackTrace();
            }

        } else if (requestCode == PICTURE_REQUEST_GALLERY) {

            // 得到图片的全路径
            Log.e("ssss", "拍照返回");
//                Uri uri = data.getData();
            Log.e("ssss", "filepath==>" + tempFile);
            Log.e("ssss", "Uri.fromFile==>" + Uri.fromFile(tempFile));
            crop(Uri.fromFile(tempFile));

        }
        super.onActivityResult(requestCode, resultCode, data);

    }

    /**
     * 剪切图片
     *
     * @param uri
     */

    private void crop(Uri uri) {
        // 裁剪图片意图
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        // 裁剪框的比例，1：1
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // 裁剪后输出图片的尺寸大小
        intent.putExtra("outputX", 250);
        intent.putExtra("outputY", 250);

        intent.putExtra("outputFormat", "JPEG");// 图片格式
        intent.putExtra("noFaceDetection", true);// 取消人脸识别
        intent.putExtra("return-data", true);
        // 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_CUT
        startActivityForResult(intent, PHOTO_REQUEST_CUT);
    }

    private void initData(Bundle savedInstanceState) {
        if (savedInstanceState != null && savedInstanceState.containsKey("tempFile")) {
            tempFile = (File) savedInstanceState.getSerializable("tempFile");
        } else {
            tempFile = new File(checkDirPath(Environment.getExternalStorageDirectory().getPath() + "/jiandan/image/"),
                    System.currentTimeMillis() + ".jpg");
        }
    }

    private static String checkDirPath(String dirPath) {
        if (TextUtils.isEmpty(dirPath)) {
            return "";
        }
        File dir = new File(dirPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        return dirPath;
    }

    //修改头像
    private void EditName(String avatar) {
        log.e("ssss", "修改头像");

        CustomProgressDialog.createDialog(mActivity).show();
        EditAvatarReq req = new EditAvatarReq();
        req.setAvatar(avatar);
        try {
            String source = req.getString();
            Rsa rsa = new Rsa();
            secret = rsa.encryptByPublic(source);
            Log.e("url", "source==" + source);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String url = Const.COMMON_ADDRESS + req.urlString() + myApplication.getDataEntity().getUuid();
        params.put("uuid", myApplication.getDataEntity().getUuid());
        params.put("token", sharedPreferencesUtil.getAccessToken());
        params.put("secret", secret);
        Log.e("ssss", "uuid==>" + myApplication.getDataEntity().getUuid());
        Log.e("ssss", "token==>" + sharedPreferencesUtil.getAccessToken());
        Log.e("ssss", "secret==>" + secret);

        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
        asyncHttpClient.put(url, params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                CustomProgressDialog.Dismiss();
                Log.e("url", "editname_json==" + response);
                String errno = response.optString("errno");
                String errmsg = response.optString("errmsg");
                if (errno.equals("000")) {
//                    myApplication.getDataEntity().setNickname(et_nickname.getText().toString());
                    if (!sharedPreferencesUtil.getOpen_id().equals("")) {
                        Oauth_login();
                    } else {
                        AutoLogin();
                    }

                } else if (errno.equals("003")) {
                    CommonUtil.showToast(mActivity, errmsg);
                    Intent intent = new Intent(mActivity, LoginActivity.class);
                    startActivityForResult(intent, 1);
                } else {
                    CommonUtil.showToast(mActivity, errmsg);
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                CustomProgressDialog.Dismiss();
                CommonUtil.showToast(mActivity, "网络连接失败");


            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        log.e("ssss1", "onResume");
        if (!sharedPreferencesUtil.getOpen_id().equals("")) {
            Oauth_login();
        } else {
            AutoLogin();
        }
    }

    private void inittype() {
        rly_store.setVisibility(View.GONE);//门店
        rly_cheques.setVisibility(View.GONE);//商家收款
        rly_business.setVisibility(View.GONE);//我的业务
        rly_application_mercha.setVisibility(View.GONE);//申请商户
        rly_identity_authentication.setVisibility(View.GONE);//身份认证
        rly_customer_service_bandcard.setVisibility(View.GONE);//我的银行卡
        rly_customer_service_qq.setVisibility(View.VISIBLE);//qq客服
        rly_customer_service_updapayid.setVisibility(View.GONE);//修改支付密码
        //判断是否身份认证
        if (myApplication.getDataEntity().getIs_certificate().equals("0") || myApplication.getDataEntity().getIs_certificate().equals("2")) {
            rly_identity_authentication.setVisibility(View.VISIBLE);//身份认证
        } else {
            rly_customer_service_updapayid.setVisibility(View.VISIBLE);//修改支付密码
        }

        //判断是否有门店
        if (myApplication.getDataEntity().getStore_id().size() > 0) {
            rly_store.setVisibility(View.VISIBLE);//门店
            rly_cheques.setVisibility(View.VISIBLE);//商家收款
            //我的银行卡
            rly_customer_service_bandcard.setVisibility(View.VISIBLE);

        } else{
            rly_store.setVisibility(View.VISIBLE);//门店
        }


        if (myApplication.getDataEntity().getLevel().equals("1")) { //登录


        }
        if (myApplication.getDataEntity().getLevel().equals("2")) {//未认证


        }
        if (myApplication.getDataEntity().getLevel().equals("3")) {//已认证


        }
        if (myApplication.getDataEntity().getLevel().equals("4")) {//商户
            rly_application_mercha.setVisibility(View.VISIBLE);//申请商户


        }
        if (myApplication.getDataEntity().getLevel().equals("5")) {//市场经理
            rly_business.setVisibility(View.VISIBLE);//我的业务


        }
        if (myApplication.getDataEntity().getLevel().equals("6")) {//区县代理
            rly_business.setVisibility(View.VISIBLE);//我的业务


        }
    }

}
